package com.wk.config;

import com.wk.annotation.LogAnnotation;
import com.wk.dao.CmfzLogDao;
import com.wk.entity.CmfzAdmin;
import com.wk.entity.CmfzLog;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration
@Aspect
public class LogAop {

    @Autowired
    private CmfzLogDao cmfzLogDao;
    //切在注解上

    @After("@annotation(com.wk.annotation.LogAnnotation)")
    public void logAfter(JoinPoint joinPoint){
        CmfzLog cmfzLog = new CmfzLog();

        //设置时间
        cmfzLog.setLogDate(new Date());


        //获取request
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //设置ip
        cmfzLog.setLogIp(request.getRemoteHost());
        //设置地址
        cmfzLog.setLogLocal(request.getRemoteUser());
        HttpSession session = request.getSession();
//        String adminName = (String) session.getAttribute("admin");

        String adminName = (String) SecurityUtils.getSubject().getPrincipal();

        if("".equals(adminName)||adminName==null){
            cmfzLog.setAdminName("透明人");
        }else {
            cmfzLog.setAdminName(adminName);
        }
        //获取签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取方法对象
        Method method = signature.getMethod();

        //获取方法上的注解
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        cmfzLog.setLogContent(annotation.content());
        cmfzLog.setLogType(annotation.type());

        //添加到数据库
        cmfzLogDao.insert(cmfzLog);
    }

}
